package com.sxz.sbs.module.sms;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.sxz.sbs.R;
import com.sxz.sbs.app.AppConstant;
import com.sxz.sbs.applibrary.component.ClearEditText;
import com.sxz.sbs.applibrary.state.StateLayout;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.event.ChoseSmsClientEvent;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.sms.adapter.ChoseSmsClientAdapter;
import com.sxz.sbs.module.sms.mode.SmsCustomBean;
import com.sxz.sbs.module.sms.presenter.ChoseSmsClientPresenter;
import com.sxz.sbs.module.sms.view.ChoseSmsClientView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 发短信---选择客户
 */
public class ChoseSmsClientActivity extends BaseActivity<ChoseSmsClientPresenter> implements ChoseSmsClientView,
        View.OnClickListener{

    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;
    @BindView(R.id.state_chose_client)
    StateLayout stateLayout;
    @BindView(R.id.rv_chose_client)
    RecyclerView rvChoseClient;
    @BindView(R.id.cb_chose_client)
    CheckBox cbChoseClient;
    @BindView(R.id.cet_sms_custom_search)
    ClearEditText cetSearch;
    private ChoseSmsClientAdapter choseSmsClientAdapter;
    private  List<SmsCustomBean> dataList = new ArrayList<>();
    private int type;
    private int starNum = 0;
    private PopupWindow popupWindow;
    private int screenWidth;
    private int screenHeight;
    private int selected = 0;
    private Map<Integer,SmsCustomBean> map = new HashMap<>();
    @Override
    protected void init() {
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();
        screenHeight = wm.getDefaultDisplay().getHeight();
        Intent intent = getIntent();
        String txt = intent.getStringExtra("client_txt");
        type = intent.getIntExtra("client_type",1);
        tvNavTitle.setText(txt);
        rvChoseClient.setLayoutManager(new LinearLayoutManager(this));
        getCustomList();
        choseSmsClientAdapter = new ChoseSmsClientAdapter(dataList);
        rvChoseClient.setAdapter(choseSmsClientAdapter);
        cetSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    InputMethodManager imm = (InputMethodManager) v.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    getCustomList();
                    return true;
                }
                return false;
            }
        });

        cbChoseClient.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cbChoseClient.isChecked()) {
                    map.clear();
                    for (int i = 0; i < dataList.size(); i++) {
                        dataList.get(i).setSelected(true);
                        map.put(i,dataList.get(i));
                    }
                    selected = dataList.size();
                    choseSmsClientAdapter.notifyDataSetChanged();
                } else {
                    map.clear();
                    for (int i = 0; i < dataList.size(); i++) {
                        dataList.get(i).setSelected(false);
                    }
                    choseSmsClientAdapter.notifyDataSetChanged();
                }
            }
        });
        choseSmsClientAdapter.setOnItemChoseClick(new ChoseSmsClientAdapter.OnItemChoseClick() {
            @Override
            public void onSelectClick(boolean isSelected, int position) {
                if (isSelected) {
                    //   选中
                    selected = selected + 1;
                    map.put(position,dataList.get(position));
                    if (selected == dataList.size()) {
                        cbChoseClient.setChecked(true);
                    }
                } else {
                   //   取消选中
                    map.remove(position);
                    selected = selected - 1;
                    cbChoseClient.setChecked(false);
                }
            }
        });
        stateLayout.setOnRetryListener(new StateLayout.OnRetryListener() {
            @Override
            public void onRetry(int state) {
                getCustomList();
            }
        });
    }
    /**
     * 获取用户列表
     */
    private void getCustomList() {
        HashMap<String,Object> map = HttpParamMap.getParamMap();
        map.put("type",type);
        map.put("txt",cetSearch.getInputValue());
        if (starNum != 0) {
            map.put("starLevel",starNum);
        }
        mPresenter.getSmsCustomList(map);
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_chose_sms_client;
    }

    @Override
    protected ChoseSmsClientPresenter createPresenter() {
        return new ChoseSmsClientPresenter();
    }

    @OnClick({R.id.iv_title_back, R.id.tv_nav_title, R.id.tv_title_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.tv_nav_title:
                View view1 = View.inflate(this, R.layout.pop_window_star_layout, null);
                setPopupWindow(view1);
                break;
            case R.id.tv_title_right:
                if (selected <= 0) {
                    ToastUtils.showShort("请选择联系人");
                    return;
                }
                EventBus.getDefault().post(new ChoseSmsClientEvent(map));
                finish();
                break;
            default:
                break;
        }
    }


    private void setPopupWindow(final View view) {
        initView(view);
        initPopupWindow(view);
    }
    private void initView(View view) {
        TextView star0 = view.findViewById(R.id.star_level_0);
        TextView star1 = view.findViewById(R.id.star_level_1);
        TextView star2 = view.findViewById(R.id.star_level_2);
        TextView star3 = view.findViewById(R.id.star_level_3);
        TextView star4 = view.findViewById(R.id.star_level_4);
        TextView star5 = view.findViewById(R.id.star_level_5);
        star0.setOnClickListener(this);
        star1.setOnClickListener(this);
        star2.setOnClickListener(this);
        star3.setOnClickListener(this);
        star4.setOnClickListener(this);
        star5.setOnClickListener(this);
    }

    /**
     * 初始化弹窗
     */
    private void initPopupWindow(View view) {
        if(popupWindow == null) {
            LinearLayout layout = new LinearLayout(this);
            LinearLayout.LayoutParams params;
             params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            view.setLayoutParams(params);
            layout.addView(view);
            layout.setBackgroundColor(Color.argb(60, 0, 0, 0));
            popupWindow = new PopupWindow(layout,screenWidth,screenHeight);
            popupWindow.setFocusable(true);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.setOutsideTouchable(true);
            popupWindow.setAnimationStyle(R.style.popup_check_anim);
            layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(popupWindow != null && popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    }
                }
            });
        }
        if (Build.VERSION.SDK_INT < 24) {
            popupWindow.showAsDropDown(tvNavTitle);
        } else {
            int[] a = new int[2];
            tvNavTitle.getLocationInWindow(a);
            popupWindow.showAtLocation(tvNavTitle, Gravity.NO_GRAVITY, 0, tvNavTitle.getHeight()+a[1]);
            popupWindow.update();
        }
    }

    @Override
    public void onGetSmsClientListSuccess(List<SmsCustomBean> data) {
      if (mIsLive) {
          cbChoseClient.setChecked(false);
          map.clear();
          selected = 0;
          if (data!= null && data.size() > 0) {
              stateLayout.showContent();
              dataList.clear();
              dataList.addAll(data);
              choseSmsClientAdapter.notifyDataSetChanged();
          } else {
              dataList.clear();
              choseSmsClientAdapter.notifyDataSetChanged();
              stateLayout.showEmpty();
          }
      }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.star_level_0:
                starNum = 0;
                break;
            case R.id.star_level_1:
                starNum = 1;
                break;
            case R.id.star_level_2:
                starNum = 2;
                break;
            case R.id.star_level_3:
                starNum = 3;
                break;
            case R.id.star_level_4:
                starNum = 4;
                break;
            case R.id.star_level_5:
                starNum = 5;
                break;
            default:
                break;
        }
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
        getCustomList();
    }
    @Override
    public void showError(int errorTag, String msg) {
        if (errorTag == AppConstant.NET_ERROR_CODE) {
            stateLayout.showNetwork();
        } else {
            stateLayout.showEmpty();
        }
    }
}
